import { _decorator, Component, Label, Button, director, instantiate, Sprite, Node } from "cc";
import { tgxSceneUtil, tgxUIMgr, tgxUIAlert } from "../../core_tgx/tgx";
import { GameMode, SubWorldEvent } from "../../module_basic/scripts/GameMgr";
import { UserMgr } from "../../module_basic/scripts/UserMgr";
import { SceneDef } from "../../scripts/SceneDef";
import { GomokuGameEvent, GomokuGameMgr } from "../scripts/GomokuGameMgr";
import { GamePlayerInfo } from "../../module_basic/scripts/GamePlayerInfo";
import { UIChat } from "../../module_basic/ui_chat/UIChat";

const { ccclass, property } = _decorator;

@ccclass('GomokuGameHUD')
export class GomokuGameHUD extends Component {

    @property(GamePlayerInfo)
    leftPlayer: GamePlayerInfo = null!;
    //#endregion

    @property(GamePlayerInfo)
    rightPlayer: GamePlayerInfo = null!;

    @property(Label)
    tips: Label = null!;

    @property(Button)
    btnReady: Button;

    @property(Node)
    watcherList: Node;

    @property(Label)
    lblTableId: Label;

    //#endregion
    //#region 组件第一次激活前执行，也就是第一次执行 update 之前触发
    start() {
        if (!UserMgr.inst.userId) {
            tgxSceneUtil.loadScene(SceneDef.START);
            return;
        }
        tgxUIMgr.inst.hideAll();

        if (GomokuGameMgr.inst.isOnline) {
            this.lblTableId.string = GomokuGameMgr.inst.data.displayId || '';
        }
        else {
            this.lblTableId.string = '';
        }
        this.initUser();
        this.initWatcherList();
        this.updateCtrlUI();
        this.initEventListener();

        if(GomokuGameMgr.inst.isOnline){
            tgxUIMgr.inst.showUI(UIChat);
        }
    }
    //#endregion

    //#region 用户信息初始化
    initUser() {
        if (GomokuGameMgr.inst.isOnline) {
            this.leftPlayer.setUserId(GomokuGameMgr.inst.leftUserId);
            this.rightPlayer.setUserId(GomokuGameMgr.inst.rightUserId);

            let u = GomokuGameMgr.inst.selfUser;
            this.btnReady.node.active = u && u.isPlayer && !u.ready;
        }
        else {
            this.btnReady.node.active = false;
            this.leftPlayer.setUserId(UserMgr.inst.userId);
            if(GomokuGameMgr.inst.gameMode == GameMode.AI){
                this.rightPlayer.setAILevel(0);
            }
            else{
                this.rightPlayer.node.active = false;
            }
        }
    }
    //#endregion

    //#region 开始注册监听事件
    initEventListener() {
        director.getScene().on(GomokuGameEvent.TURN_PLAYER_CHANGED, this.updateCtrlUI, this);
        director.getScene().on(SubWorldEvent.NEW_USER_COMES, this.onNewUserComes, this);
        director.getScene().on(SubWorldEvent.USER_DATA_CHANGED, this.onUserDataChanged, this);
        director.getScene().on(SubWorldEvent.USER_LEAVES, this.onUserLeaves, this);
        director.getScene().on(SubWorldEvent.WATCHER_LIST_CHANGED, this.initWatcherList, this);
    }

    protected onDestroy(): void {
    }
    //#endregion

    onNewUserComes(data) {
        if (data.isPlayer) {
            this.initUser();
        }
        else {
            this.initWatcherList();
        }
    }

    onUserLeaves(data) {
        if (data.isPlayer) {
            this.initUser();
        }
        else {
            this.initWatcherList();
        }
    }

    onUserDataChanged(data){
        this.initUser();
        if (data.isPlayer !== undefined) {
            this.initWatcherList();            
        }
    }

    async initWatcherList() {
        this.watcherList.parent.active = false;
        let usersData = GomokuGameMgr.inst.data?.userList;
        if (!GomokuGameMgr.inst.isOnline || !usersData.length) {
            return;
        }

        this.watcherList.parent.active = true;

        for (let i = 0; i < this.watcherList.children.length; ++i) {
            this.watcherList.children[i].active = false;
        }

        let userIds = [];
        let c = this.watcherList.children[0];
        for (let i = 0; i < usersData.length; ++i) {
            let u = usersData[i];
            if(!u.isPlayer){
                let newNode = instantiate(c);
                this.watcherList.addChild(newNode);
                userIds.push(u.uid);
            }
        }

        await UserMgr.inst.rpc_GetUserInfos(userIds);

        for (let i = 0; i < userIds.length; ++i) {
            let c = this.watcherList.children[i];
            c.active = true;
            let icon = c.children[0].getComponent(Sprite);
            UserMgr.inst.setUserIconAndName(userIds[i], icon);
        }
    }

    updateCtrlUI() {
        if (GomokuGameMgr.inst.gameMode == GameMode.SOLO) {
            this.tips.string = '单人练习';
        }
        else if (GomokuGameMgr.inst.isWatcher) {
            this.tips.string = '观战中...';
        }
        else if (GomokuGameMgr.inst.data.playerNum < 2) {
            this.tips.string = '等待对手加入...'
        }
        else if (GomokuGameMgr.inst.isMyTurn) {
            this.tips.string = '该你落子...';
        }
        else {
            this.tips.string = '对手落子...';
        }
    }

    async onBtnExitClicked() {
        if (!GomokuGameMgr.inst.isOnline) {
            tgxUIAlert.show('球局未结束，确定离开吗？', true).onClick((ok: boolean) => {
                if (ok) {
                    tgxSceneUtil.loadScene(SceneDef.LOBBY_GOMOKU);
                }
            });
        }
        else {
            if (GomokuGameMgr.inst.isPlayer && GomokuGameMgr.inst.isPlaying) {
                tgxUIAlert.show('确定要认输并退出吗？', true).onClick(async (ok: Boolean) => {
                    if (ok) {
                        let ret = await GomokuGameMgr.inst.rpc_LeaveTable();
                        if (ret.isSucc) {
                            tgxSceneUtil.loadScene(SceneDef.LOBBY_GOMOKU);
                        }
                        else {
                            tgxUIAlert.show('不能离开');
                        }
                    }
                });
            }
            else {
                let ret = await GomokuGameMgr.inst.rpc_LeaveTable();
                if (ret.isSucc || (ret.err.code == 'LOST_CONN' && ret.err.message == 'USER_LEAVE')) {
                    tgxSceneUtil.loadScene(SceneDef.LOBBY_GOMOKU);
                }
                else {
                    tgxUIAlert.show(ret.err.message);
                }
            }
        }
    }
}
